/**
 *  @auth: sce
 *  @date: 17-12-31
 *  @desc:
 **/
import {query} from './../services/menu';

export const MENU_INITIATE_REQUEST = 'MENU_INITIATE_REQUEST'; //准备发起请求
export const MENU_REJECT_REQUEST = 'MENU_REJECT_REQUEST';   //请求失败
export const MENU_RESOLVE_REQUEST = 'MENU_RESOLVE_REQUEST';   //请求成功

export const initQueryMenu = () => ({
    type : MENU_INITIATE_REQUEST
});

export const rejectQueryMenu = () => ({
    type : MENU_REJECT_REQUEST
});

export const resolveQueryMenu = (data) => ({
    type : MENU_RESOLVE_REQUEST,
    menuList : data,
    resolveAt : Date.now()
});

const queryMenu = () => dispatch => {
    dispatch(initQueryMenu());
    return query()
        .then(data => {
            return dispatch(resolveQueryMenu(data));
        })
        .catch(() => dispatch(rejectQueryMenu()))
};

const shouldQuery = (state) => {
    const { hasMenu, isLoading } = state.menuReducer;
    if(hasMenu || isLoading) return false;
    return true;
};

export const queryMenuIfNeed = () => (dispatch, getState) => {
    if(shouldQuery(getState())){
        return dispatch(queryMenu())
    }
};